<script setup>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
	isLoading: Boolean,
	selectedElements: Array,
	elementalGroup: String,
})

const emit = defineEmits(['on-submit'])

const formRef = ref(null)

// 判断是二元还是三元计算
const isBinary = computed(() => props.selectedElements?.length === 2)

// 表单数据
const form = ref({
	pressure: 101325,
	temperature: 600,
	comp1_value: isBinary.value ? 0.5 : 0.4, // 第一个元素成分
	comp2_value: isBinary.value ? 0.5 : 0.3, // 第二个元素成分
	comp3_value: isBinary.value ? 0 : 0.3, // 第三个元素成分（三元时使用）
})

// 验证规则
const validationRules = computed(() => ({
	pressure: [
		{ required: true, message: '请输入压强', trigger: 'blur' },
		{ type: 'number', message: '压强必须为数字', trigger: 'blur' },
	],
	temperature: [
		{ required: true, message: '请输入温度', trigger: 'blur' },
		{ type: 'number', message: '温度必须为数字', trigger: 'blur' },
	],
	comp1_value: [
		{
			required: true,
			message: `请输入${props.selectedElements[0]}成分`,
			trigger: 'blur',
		},
		{
			validator: (_, value, callback) => {
				const num = Number(value)
				if (isNaN(num) || num < 0 || num > 1) {
					callback(new Error('成分值必须在0到1之间'))
				} else if (!isBinary.value && num + form.value.comp2_value > 1) {
					callback(
						new Error(
							`${props.selectedElements[0]}和${props.selectedElements[1]}成分总和不能超过1`
						)
					)
				} else {
					callback()
				}
			},
			trigger: 'blur',
		},
	],
	comp2_value: [
		{
			required: true,
			message: `请输入${props.selectedElements[1]}成分`,
			trigger: 'blur',
		},
		{
			validator: (_, value, callback) => {
				const num = Number(value)
				if (isNaN(num) || num < 0 || num > 1) {
					callback(new Error('成分值必须在0到1之间'))
				} else if (!isBinary.value && num + form.value.comp1_value > 1) {
					callback(
						new Error(
							`${props.selectedElements[0]}和${props.selectedElements[1]}成分总和不能超过1`
						)
					)
				} else {
					callback()
				}
			},
			trigger: 'blur',
		},
	],
}))

// 自动计算剩余成分
watch(
	() => [form.value.comp1_value, form.value.comp2_value],
	() => {
		if (isBinary.value) {
			form.value.comp2_value = Number((1 - form.value.comp1_value).toFixed(4))
		} else {
			form.value.comp3_value = Number(
				(1 - form.value.comp1_value - form.value.comp2_value).toFixed(4)
			)
		}
	},
	{ immediate: true }
)

// 提交表单
const submitForm = async () => {
	try {
		await formRef.value.validate()

		const submitData = {
			tdb: props.elementalGroup + '.tdb',
			elements: props.selectedElements,
			temperature: form.value.temperature,
			pressure: form.value.pressure,
			comp1: props.selectedElements[0],
			comp1_value: form.value.comp1_value,
		}

		if (!isBinary.value) {
			submitData.comp2 = props.selectedElements[1]
			submitData.comp2_value = form.value.comp2_value
		}

		emit('on-submit', submitData)
	} catch (error) {
		ElMessage.error('请检查表单输入')
	}
}
// 重置表单
const resetForm = () => {
	formRef.value?.resetFields()
	form.value = {
		pressure: 101325,
		temperature: 600,
		comp1_value: isBinary.value ? 0.5 : 0.4,
		comp2_value: isBinary.value ? 0.5 : 0.3,
		comp3_value: isBinary.value ? 0 : 0.3,
	}
}
</script>

<template>
	<div class="component-form">
		<el-form
			ref="formRef"
			:model="form"
			:rules="validationRules"
			label-width="100px"
		>
			<!-- 温度和压强 -->
			<el-form-item label="温度(K)" prop="temperature">
				<div class="tempStyle">
					<el-input-number
						v-model="form.temperature"
						:precision="2"
						:min="298.15"
						:max="2000"
						placeholder="600"
						:controls="false"
						class="inputNumber"
					/>
					<span class="text">温度(K)：289.15K ～ 2000K</span>
				</div>
			</el-form-item>

			<el-form-item label="压强(Pa)" prop="pressure">
				<el-input-number
					v-model="form.pressure"
					:precision="4"
					:min="0"
					placeholder="600"
					:controls="false"
					class="inputNumber"
				/>
			</el-form-item>

			<!-- 元素1成分 -->
			<el-form-item :label="`${selectedElements[0]}成分`" prop="comp1_value">
				<el-input-number
					v-model="form.comp1_value"
					:precision="4"
					:min="0.01"
					:max="1"
					:placeholder="isBinary ? '0.5' : '0.4'"
					:controls="false"
					class="inputNumber"
				/>
			</el-form-item>

			<!-- 元素2成分 -->
			<el-form-item :label="`${selectedElements[1]}成分`" prop="comp2_value">
				<el-input-number
					v-model="form.comp2_value"
					:precision="4"
					:min="0.01"
					:max="1"
					:placeholder="isBinary ? '0.5' : '0.3'"
					:controls="false"
					class="inputNumber"
				/>
			</el-form-item>

			<!-- 元素3成分（三元时显示） -->
			<el-form-item
				v-if="!isBinary"
				:label="`${selectedElements[2]}成分`"
				title="自动计算"
			>
				<el-input-number
					:model-value="form.comp3_value"
					:precision="4"
					:min="0.01"
					:max="1"
					readonly
					placeholder="自动计算"
					disabled
					:controls="false"
					class="inputNumber"
				/>
			</el-form-item>
		</el-form>

		<div class="form-actions">
			<el-button size="small" @click="resetForm">重置</el-button>
			<el-button
				type="primary"
				size="small"
				:loading="isLoading"
				@click="submitForm"
			>
				计算
			</el-button>
		</div>
	</div>
</template>

<style scoped lang="scss">
.form-actions {
	display: flex;
	justify-content: center;
	gap: 10px;
	margin-top: 20px;

	.el-button {
		flex: 1;
	}
}

:deep(.el-form-item) {
	margin-bottom: 20px !important;
	.el-form-item__error {
		display: block !important;
	}
}

:deep(.inputNumber) {
	width: 100% !important;
	.el-input__wrapper {
		padding: 1px 11px !important;
		.el-input__inner {
			text-align: left;
		}
	}
}

.tempStyle {
	position: relative;
	width: 100%;
	.text {
		position: absolute;
		font-size: 0.75rem;
		bottom: -26.7px;
		right: 0;
	}
}
</style>

<style>
@import url('@/styles/element-plus/form.scss');
</style>
